let Koa = require('koa');
let app = new Koa();
let router = require('koa-router')();
let bodyparser = require('koa-bodyparser');
let query = require('./sql/query');
router.get('/list', async ctx => {
    let res = await query(`select * from week2`);
    ctx.body = {
        code: 1,
        data: res
    }
})

router.post('/add', async ctx => {
    let { menu, name } = ctx.request.body;
    if (!menu || !name) {
        ctx.body = {
            code: 0,
            msg: '缺少参数'
        }
        return;
    }
    let res = await query(`insert into week2 (name,menu,flag) values('${name}','${menu}',${0})`);
    console.log(res)
    if (res.affectedRows) {
        ctx.body = {
            code: 1,
            msg: '添加成功'
        }
    }
})

router.post('/show', async ctx => {
    let { id, flag } = ctx.request.body;
    console.log(id, flag)
    let res = await query(`update week2 set flag=${flag} where id=${id}`);
    console.log(res);
    ctx.body = {
        code: 1,
        msg: '修改成功'
    }
})

router.post('/delete', async ctx => {
    let { id } = ctx.request.body;
    let res = await query(`delete from week2 where id=${id} `);
    console.log(res)
    ctx.body = {
        code: 1,
        msg: '删除成功'
    }
})

router.get('/editinfo', async ctx => {
    console.log(ctx.query)
    let { id } = ctx.query;
    console.log(id)
    let res = await query(`select * from week2 where id=${id}`);
    console.log(res)
    ctx.body = {
        code: 1,
        data: res
    }
})

router.post('/edit', async ctx => {
    console.log(ctx)
    let { id, name, menu } = ctx.request.body;
    if (!name || !menu) {
        ctx.body = {
            code: 0,
            msg: '缺少参数'
        }
        return;
    }
    let res = await query(`update week2 set name='${name}',menu='${menu}' where id=${id}`);
    console.log(res)
    ctx.body = {
        code: 1,
        msg: '修改成功'
    }
})

app.use(bodyparser());
app.use(router.routes(), router.allowedMethods());
app.listen(3030)